using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace CustomWorkflowActivities
{
    /// <summary>
    /// wrapper class to safely use Mutexes with a using statement
    /// usage:
    /// 
    /// static Mutex mutex = new Mutex( false, #some machine global name#);
    /// 
    /// ...
    /// 
    /// using ( WaitHandleSentry sentry = new WaitHandleSentry( mutex) )
    /// {
    ///     // do stuff protected from other threads
    /// }
    /// </summary>
    public class WaitHandleSentry : IDisposable
    {
        private WaitHandle _handle;
        public WaitHandleSentry(Mutex handle)
        {
            _handle = handle;
            _handle.WaitOne();
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (_handle is Mutex)
            {
                ((Mutex)_handle).ReleaseMutex();
            }
            else if (_handle is Semaphore)
            {
                ((Semaphore)_handle).Release();
            }
        }

        #endregion
    }
}
